import java.net.*;
import java.io.*;
import java.util.Properties;


import org.joda.time.*
import org.joda.time.format.*
import org.joda.time.format.DateTimeFormat
import org.apache.commons.io.*


class Utils
{
    static def String getFormattedDateTime(DateTime date)
    {
        def DateTimeZone timezone = DateTimeZone.forTimeZone(TimeZone.getTimeZone("America/Chicago"))
        def now = new DateTime(timezone)

        def DateTimeFormatter f
        def fb = new DateTimeFormatterBuilder().appendDayOfMonth(1)
        fb = fb.appendLiteral(" ")
        fb = fb.appendMonthOfYearText()
        fb = fb.appendLiteral(" ")
        fb = fb.appendYear(2, 4)
        fb = fb.appendLiteral(" ")
        fb = fb.appendHourOfDay(2)
        fb = fb.appendLiteral(":")
        fb = fb.appendMinuteOfHour(2)
        fb = fb.appendLiteral(":")
        fb = fb.appendSecondOfMinute(2)
        fb = fb.appendLiteral(" GMT-0600")

        f = fb.toFormatter()

        return f.print(date)
    }

    static def String getFormattedMMDDYYDate(DateTime date)
    {
        def DateTimeZone timezone = DateTimeZone.forTimeZone(TimeZone.getTimeZone("America/Chicago"))
        def now = new DateTime(timezone)

        def DateTimeFormatter f
        def fb = new DateTimeFormatterBuilder().appendMonthOfYear(1)
        fb = fb.appendLiteral("/")
        fb = fb.appendDayOfMonth(1)
        fb = fb.appendLiteral("/")
        fb = fb.appendYear(2, 4)

        f = fb.toFormatter()

        return f.print(date)
    }

    static boolean parseBoolean(String truefalseStr)
    {
        return (truefalseStr!=null && truefalseStr.equalsIgnoreCase("y"))?true:false
    }

    static def DateTime parseDateString(String dateTimeStr)
    {
        String pattern = "MM/dd/yy"

        DateTimeFormatter formatter = DateTimeFormat.forPattern(pattern)

        DateTime dt = formatter.parseDateTime(dateTimeStr)

        return dt
    }

    static def DateTime parseTimeString(String dateTimeStr)
    {
        String pattern = "HH:mm:ss"

        DateTimeFormatter formatter = DateTimeFormat.forPattern(pattern)

        DateTime time = formatter.parseDateTime(dateTimeStr)

        return time
    }

    static def DateTime parseDateTimeString(String dateTimeStr)
    {
        String pattern = "MM/dd/yy HH:mm:ss"

        DateTimeFormatter formatter = DateTimeFormat.forPattern(pattern)

        DateTime time = formatter.parseDateTime(dateTimeStr)

        return time
    }

    static def String readTrimmedStr(String value)
    {
        def String result = ""

        if(value != null)
        {
            result = value

            result = result.replace('\n', ' ')
            result = result.replace('\r', ' ')
            //result = result.replace('&', ' and ')
            result = result.replace('/', '&')
            result = result.replace('\\', ' ')
        }

        return result
    }

    
    // read the OD string and break it up
    static def int readODStr(str)
    {
        def int offset = 0;
        
        def offsetStr = str != null ? str:""

        if(offsetStr.length() > 0)
        {
            offsetStr = offsetStr.trim().minus(" ").replace("OD","")
            offsetStr = offsetStr.minus("+")
            if(offsetStr.size()==0)
                offsetStr = "0"
            offset = offsetStr.toInteger();
        }
        
        return offset;
    }


    // read the time string and break it up
    static def int[] readTimeStr(String str)
    {
        def arr = []
        def int[] arrint = [0,0]

        if(str != null && str.length() > 0)
        {
            arr = str.split(":")

            arrint[0] = java.lang.Integer.parseInt(arr[0])
            arrint[1] = java.lang.Integer.parseInt(arr[1])
        }

        return arrint
    }


    // read the OD+x string and break it up
    static def int readODStr(String str)
    {
        def int offset = 0;
        
        if(str!=null && str.length() > 0)
        {
            def offsetStr = str.trim().minus(" ").replace("OD","")

            offsetStr = offsetStr.minus("+")
            if(offsetStr.size()==0)
                offsetStr = "0"

            offset = offsetStr.toInteger();
        }
 
        return offset;
    }


    static boolean isRemoteHttp(String path)
    {
        return path.contains("http://")
    }


    static boolean fileExistsLocalOrRemote(String path)
    {
        boolean result = false
        try 
        {
            if(isRemoteHttp(path))
            {
                HttpURLConnection.setFollowRedirects(false)

                // note : you may also need
                //        HttpURLConnection.setInstanceFollowRedirects(false)
                HttpURLConnection con = (HttpURLConnection) new URL(path).openConnection()
                con.setRequestMethod("HEAD")
                
                //println con.getResponseCode()
                
                result = (con.getResponseCode() == HttpURLConnection.HTTP_OK)
            }
            else
            {
                result = new File(new File(path).getCanonicalPath()).exists()
            }
        }
        catch (Exception e) 
        {
            e.printStackTrace();
            result = false
        }
        
        return result
    }


    static String readFileLocalOrRemote(String path)
    {
        def text = ""

        if(!isRemoteHttp(path))
        {
            text = new File( new File(path).getCanonicalPath() ).getText()
        }
        else
        {
            text = new URL(path).getText()
        }

        return text
    }


    static void copyFileLocalOrRemote(String path, String resultFilePath)
    {
        String text = readFileLocalOrRemote(path)

        new File(resultFilePath).write(text)
    }


    static String launchProcess(String processStr)
    {
        def proc1 = processStr.execute()
        StringBuffer output = new StringBuffer()
        StringBuffer err = new StringBuffer()
        //proc1.consumeProcessOutput(output, err)
        proc1.waitFor()
        if (proc1.exitValue())
            print proc1.err.text
        else
            print proc1.text
        //println "output:"+output
        //println "error:"+err
    }


    /**
    * utility to set proxy for checking to see if remote url exists
    */
    /*
    static boolean exists(String URLName){
        try {
          Properties systemSettings = System.getProperties();
          systemSettings.put("proxySet", "true");
          systemSettings.put("http.proxyHost","proxy.mycompany.local") ;
          systemSettings.put("http.proxyPort", "80") ;

          URL u = new URL(URLName);
          HttpURLConnection con = (HttpURLConnection) u.openConnection();
          //
          // it's not the greatest idea to use a sun.misc.* class
          // Sun strongly advises not to use them since they can 
          // change or go away in a future release so beware.
          //
          sun.misc.BASE64Encoder encoder = new sun.misc.BASE64Encoder();
          String encodedUserPwd =
             encoder.encode("domain\\username:password".getBytes());
          con.setRequestProperty
             ("Proxy-Authorization", "Basic " + encodedUserPwd);
          con.setRequestMethod("HEAD");
          System.out.println
             (con.getResponseCode() + " : " + con.getResponseMessage());
          return (con.getResponseCode() == HttpURLConnection.HTTP_OK);
        }
        catch (Exception e) {
          e.printStackTrace();
          return false;
        }
    }
    */


    static void main(args)
    {
        DateTime dt = Utils.parseDateString("1/01/01")
        println dt

        DateTime time = Utils.parseTimeString("23:01:01")
        println time

        dt = Utils.parseDateTimeString("1/01/01 23:01:01")
        println dt

        println(new URL("http://www.google.com").getText())
        //println(new File("./Outline.txt").getText())

        println isRemoteHttp("http://www.google.com/index.html")

        launchProcess("ls")

        println "FileExists Local or Remote:" + fileExistsLocalOrRemote("http://www.google.com")
        println "FileExists Local or Remote:" + fileExistsLocalOrRemote("Utils.groovy")
    }
}
